package com.okay.window

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log


class HomeKeyListener(context: Context) {
    private val mContext: Context
    private val mFilter: IntentFilter
    private var mListener: OnHomePressedListener? = null
    private var mRecevier: HomeKeyRecevier? = null

    // 回调接口
    interface OnHomePressedListener {
        fun onHomePressed()
        fun onHomeLongPressed()
    }

    /**
     * 设置监听
     *
     * @param listener
     */
    fun setOnHomePressedListener(listener: OnHomePressedListener?) {
        mListener = listener
        mRecevier = HomeKeyRecevier()
    }

    /**
     * 开始监听，注册广播
     */
    fun startWatch() {
        if (mRecevier != null) {
            mContext.registerReceiver(mRecevier, mFilter)
        }
    }

    /**
     * 停止监听，注销广播
     */
    fun stopWatch() {
        if (mRecevier != null) {
            mContext.unregisterReceiver(mRecevier)
        }
    }

    /**
     * 广播接收者
     */
    internal inner class HomeKeyRecevier : BroadcastReceiver() {
        val SYSTEM_DIALOG_REASON_KEY = "reason"
        val SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions"
        val SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps"
        val SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"
        override fun onReceive(context: Context?, intent: Intent) {
            val action = intent.action
            if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
                val reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY)
                if (reason != null) {
                    Log.e(TAG, "action:$action,reason:$reason")
                    if (mListener != null) {
                        if (reason == SYSTEM_DIALOG_REASON_HOME_KEY) {
                            // 短按home键
                            mListener!!.onHomePressed()
                            Log.e(TAG, "action:点击")
                        } else if (reason == SYSTEM_DIALOG_REASON_RECENT_APPS
                        ) {
                            // 长按home键
                            mListener!!.onHomeLongPressed()

                            Log.e(TAG, "action:长按")
                        }
                    }
                }
            }
        }
    }

    companion object {
        const val TAG = "HomeKeyWatcher"
    }

    init {
        mContext = context
        mFilter = IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
    }
}